package com.audaque.springboot.foshanupload.httpclient.model;


import com.audaque.springboot.foshanupload.core.result.R;
import com.audaque.springboot.foshanupload.httpclient.handler.HttpClientResponseHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;


import java.io.IOException;
import java.util.Objects;

/**
 * @author zgb
 * @desc 封装HTTP状态码, 让http请求不抛异常
 * @date 2022-05-09 18:54:32
 */
@Slf4j
public class ExtractHttpClient {
    @Autowired
    private HttpClient httpClient;
    @Autowired
    private HttpClientResponseHandler httpClientResponseHandler;


    public <T> R<T> executeFinallyNotClose(HttpUriRequest request)
            throws Exception {
        R<T> r = new R<T>();
        r.setSuccess(false);
        r.setCode("400");
        r.setData(null);
        HttpResponse response = null;
        try {
            response = httpClient.execute(request);
        } catch (Exception e) {
            e.printStackTrace();
            String msg = String.format("httpClient.execute调用%s失败,异常信息：%s", request.getURI(), e.getMessage());
            log.error(msg);
            r.setMsg(msg);
            // 确保实体内容已完全使用，并且内容流（如果存在）已关闭
            final HttpEntity entity = response.getEntity();
            EntityUtils.consume(entity);
            return r;
        }
        try {
            r = (R) httpClientResponseHandler.handleResponse(response);
        } catch (Exception e) {
            e.printStackTrace();
            String msg = "HttpClient结果处理异常:" + e.getMessage();
            log.error(msg);
            r.setMsg(msg);
            // 确保实体内容已完全使用，并且内容流（如果存在）已关闭
            final HttpEntity entity = response.getEntity();
            EntityUtils.consume(entity);
            return r;
        }

        // 确保实体内容已完全使用，并且内容流（如果存在）已关闭
        final HttpEntity entity = response.getEntity();
        EntityUtils.consume(entity);
        return r;
    }


    public <T> R<T> executeFinallyClose(HttpUriRequest httpUriRequest) throws IOException {
        R<T> r = new R<T>();
        r.setSuccess(false);
        r.setCode("400");
        r.setData(null);
        CloseableHttpResponse closeableHttpResponse = null;
        CloseableHttpClient closeableHttpClient = ((CloseableHttpClient) httpClient);
        try {
            closeableHttpResponse = closeableHttpClient.execute(httpUriRequest);
        } catch (Exception e) {
            e.printStackTrace();
            String msg = String.format("closeableHttpClient.execute调用%s失败,异常信息：%s", httpUriRequest.getURI(), e.getMessage());
            log.error(msg);
            r.setMsg(msg);
            return r;
        } finally {
            // 5、关闭资源
            if (closeableHttpResponse != null) {
                try {
                    //obj.close();//只修改它的状态，obj还不是null，还可以重新开启它
                    closeableHttpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    String msg = "CloseableHttpResponse关闭异常:" + e.getMessage();
                    log.error(msg);
                    r.setMsg(msg);
                }
            }
            if (httpClient != null) {
                try {
                    //obj.close();//只修改它的状态，obj还不是null，还可以重新开启它
                    closeableHttpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    String msg = "CloseableHttpClient关闭异常:" + e.getMessage();
                    log.error(msg);
                    r.setMsg(msg);
                }
            }
        }


        if (closeableHttpResponse == null) {
            r.setMsg("httpResponse == null");
            return r;
        }
        log.debug("httpResponse：" + closeableHttpResponse);
        StatusLine statusLine = closeableHttpResponse.getStatusLine();
        if (statusLine == null) {
            r.setMsg("statusLine == null");
            return r;
        }
        log.debug("statusLine：" + statusLine);
        int statusCode = statusLine.getStatusCode();
        log.debug("statusCode：" + statusCode);
        String reasonPhrase = statusLine.getReasonPhrase();
        log.debug("reasonPhrase：" + reasonPhrase);
        org.apache.http.HttpEntity entity = closeableHttpResponse.getEntity();
        log.debug("entity：" + entity);
        Header[] allHeaders = closeableHttpResponse.getAllHeaders();
        log.debug("allHeaders：" + allHeaders);

        String responseJson = EntityUtils.toString(entity, "UTF-8");
        r.setData((T) responseJson);
        r.setMsg(reasonPhrase);
        r.setCode(Integer.toString(statusCode));
        if (Objects.equals(statusCode, 200)) {
            r.setSuccess(true);
        } else {
            r.setSuccess(false);
        }

        return r;
    }


}
